//
//  GRMyCollectionViewController.m
//  YC_GRice
//
//  Created by Feng Liu on 2018/8/30.
//  Copyright © 2018年 YeCai. All rights reserved.
//

#import "GRMyCollectionViewController.h"
#import "GRCollectionShopViewCell.h"
#import "GRLocalDiscountViewCell.h"
#import "GRHotMsgViewCell.h"

#import "GRPayBillViewController.h"
#import "GRStoreViewController.h"
#import "GRGoodDetailPageVC.h"
#import "GRNewsDetailViewController.h"

@interface GRMyCollectionViewController () <GRBasisProtocol>
{
    CGFloat discountHeight; CGFloat shopHeight;
}
@property (nonatomic, strong) UIView *collectSegment;
@property (nonatomic, strong) UILabel *slideLine;

@property (nonatomic, strong) NSMutableArray *collectionList;

@end

@implementation GRMyCollectionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.commontitle     = @"我的收藏";
    shopHeight            = 22 / 75.0 * KscreenWidth;
    discountHeight       = 6 / 25.0 * KscreenWidth;
    
    self.collectSegment = [[UIView alloc] initWithFrame:CGRectMake(0, self.commonHeader.y + self.commonHeader.height, KscreenWidth, 35)];
    self.collectSegment.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectSegment];
    
    NSArray *titleArr   = @[@"商家", @"同城优惠", @"热门资讯"];
    self.slideLine          = [[UILabel alloc] init];
    self.slideLine.backgroundColor = KGMTHEM_COLOR;
    [self.collectSegment addSubview:self.slideLine];
    WEAKSELF
    for (int i = 0; i < 3; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame      = CGRectMake(KscreenWidth/3*i, 0, KscreenWidth/3, 35);
        button.tag          = i + 100;
        [button setTitle:titleArr[i] forState:UIControlStateNormal];
        [button setTitleColor:KGMGRAY_COLOR forState:UIControlStateNormal];
        [button setTitleColor:KGMBLACK_COLOR forState:UIControlStateSelected];
        [button addTarget:self action:@selector(didClickCollectionType:) forControlEvents:UIControlEventTouchUpInside];
        [self.collectSegment addSubview:button];
        
        if (i == 0) {
            button.titleLabel.font = [UIFont boldSystemFontOfSize:15];
            [self.slideLine mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.mas_equalTo(button.mas_centerX);
                make.bottom.mas_equalTo(weakSelf.collectSegment.mas_bottom);
                make.size.mas_equalTo(CGSizeMake(30, 3));
            }];
        }else {
            button.titleLabel.font = [UIFont systemFontOfSize:15];
        }
    }
    // Do any additional setup after loading the view.
    self.tableView.frame = CGRectMake(0, self.collectSegment.y + self.collectSegment.height, KscreenWidth, KscreenHeight-self.collectSegment.y - self.collectSegment.height);
    [self.tableView registerNib:[UINib nibWithNibName:@"GRCollectionShopViewCell" bundle:nil] forCellReuseIdentifier:@"GRCollectionShopViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"GRLocalDiscountViewCell" bundle:nil] forCellReuseIdentifier:@"GRLocalDiscountViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"GRHotMsgViewCell" bundle:nil] forCellReuseIdentifier:@"GRHotMsgViewCell"];
    
    [self getCollectionList];
    [self MJRefresh];
}

static NSString *type = @"shop";
static NSInteger pageIndex = 1;
- (void)getCollectionList {
    [GRHUD showLoading:@"正在加载" atView:self.view];
    CLLocationCoordinate2D coordinate = [GRLocationManager defaultManager].currentLocation;
    NSDictionary *paramer = @{@"coordinates" : @[@(coordinate.longitude), @(coordinate.latitude)],
                              @"currentPage" : @(pageIndex),
                              @"pageSize"     : @10,
                              @"profileId"      : [GRUserBasisInfo BasisID],
                              @"type"           : type
                              };
    WEAKSELF
    [GRUserAction getMyCollectionWithParamer:paramer isInstallment:NO completionHandler:^(BOOL success, id responseObject, GRError *error) {
        if (success) {
            if (pageIndex == 1) {
                [weakSelf.collectionList removeAllObjects];
            }
            [weakSelf.collectionList addObjectsFromArray:responseObject];
            [weakSelf.tableView reloadData];
        }else {
            [GRHUD showMessage:error.errorMsg atView:weakSelf.view];
        }
        
        [GRHUD dismissHUD:weakSelf.view];
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
}

- (void)MJRefresh {
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        pageIndex = 1;
        [self getCollectionList];
    }];
    
    self.tableView.mj_footer  = [GRRefreshBackFooter footerWithRefreshingBlock:^{
        pageIndex += 1;
        [self getCollectionList];
    }];
}

static NSInteger lastTag = 100;
- (void)didClickCollectionType:(UIButton *)sender {
    if (sender.tag != lastTag) {
        UIButton *lastBtn = [self.collectSegment viewWithTag:lastTag];
        lastBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        lastBtn.selected   = NO;
        sender.selected    = YES;
        sender.titleLabel.font  = [UIFont boldSystemFontOfSize:15];
        WEAKSELF
        [UIView animateWithDuration:.3 animations:^{
            weakSelf.slideLine.centerX = sender.centerX;
        }];
        
        [self changeTypeAtIndex:sender.tag];
        lastTag             = sender.tag;
        pageIndex          = 1;
        [self getCollectionList];
    }
}

- (void)changeTypeAtIndex:(NSInteger)index {
    switch (index) {
        case 100:
            type = @"shop";
            break;
            
        case 101:
            type = @"good";
            break;
            
        case 102:
            type = @"news";
            break;

        default:
            break;
    }
}

#pragma Mark ------------   UITableViewDelegate， UITableViewDataSource  --------------
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.collectionList.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GRCollectionCommonViewCell *cell = nil;
    switch (lastTag) {
        case 100:{
            cell    = [tableView dequeueReusableCellWithIdentifier:@"GRCollectionShopViewCell" forIndexPath:indexPath];
        }
            break;
            
        case 101:{
            cell    = [tableView dequeueReusableCellWithIdentifier:@"GRLocalDiscountViewCell" forIndexPath:indexPath];
        }
            break;
            
        default:{
            cell    = [tableView dequeueReusableCellWithIdentifier:@"GRHotMsgViewCell" forIndexPath:indexPath];
        }
            break;
    }
    cell.delegate      = self;
    cell.collectModel = self.collectionList[indexPath.row];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (lastTag == 101) {
        return discountHeight;
    }else {
        return shopHeight;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    GRCollectCommonModel *model            = self.collectionList[indexPath.row];
    if (model.showCancleButton) {
        GRCollectionCommonViewCell *cell    = [tableView cellForRowAtIndexPath:indexPath];
        [cell showCancle:NO];
    }else {
        switch (lastTag) {
            case 100:{
                if ([GRUserBasisInfo isLogin]) {
                    GRPayBillViewController *billVc  = [[GRPayBillViewController alloc] init];
                    billVc.storeId                          = model.relateId;
                    //                GRStoreViewController *storeVc = [[GRStoreViewController alloc] init];
                    //                storeVc.storeId                        = model.relateId;
                    billVc.isValid = YES;
                    [self.navigationController pushViewController:billVc animated:YES];
                }else{
                    [self goToLogin];

                }
            }
                break;
                
            case 101:{
                GRGoodDetailPageVC *goodVc = [[GRGoodDetailPageVC alloc] init];
                goodVc.goodId                      = model.relateId;
                [self.navigationController pushViewController:goodVc animated:YES];
            }
                break;
                
            default:{
                GRNewsDetailViewController *newsVc = [[GRNewsDetailViewController alloc] init];
                newsVc.newsId                                = model.relateId;
                newsVc.type                                   = model.typeInt;
                [self.navigationController pushViewController:newsVc animated:YES];
            }
                break;
        }
    }
}

-(void)deleteRowAtTableViewCell:(UITableViewCell *)cell {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    if (indexPath) {
        [self.collectionList removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSMutableArray *)collectionList {
    if (!_collectionList) {
        _collectionList = [NSMutableArray array];
    }
    return _collectionList;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
